package com.book.dao.impl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.book.bean.Book;
import com.book.bean.Users;
import com.book.dao.UserDao;
import com.book.util.DBUtil;


public class UserDaoImpl implements UserDao {

	@Override
	public boolean register(Users user) throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "insert into users(uname,password,email,IDnumber,phone,postcode,address) values(?,?,?,?,?,?,?)";
		
		ArrayList<Object> param = new ArrayList<Object>();
		param.add(user.getUname());
		param.add(user.getPassword());
		param.add(user.getEmail());
		param.add(user.getIDnumber());
		param.add(user.getPhone());
		param.add(user.getPostcode());
		param.add(user.getAddress());
		
		return DBUtil.add(sql, param) > 0;
	}

	@Override
	public int login(String uname, String password) throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "select * from users where uname=? and password=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, uname);
		ps.setString(2, password);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			return rs.getInt(1);
		}
		return 0;
	}

	@Override
	public Users getUsers(String uname) throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "select uid,uname,password,email,IDnumber,phone,postcode,address from users where uname=?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setString(1, uname);
		ResultSet rs = psmt.executeQuery();
		while (rs.next()) {
			Users user = new Users();
			user.setUid(rs.getInt(1));
			user.setUname(rs.getString(2));
			user.setPassword(rs.getString(3));
			user.setEmail(rs.getString(4));
			user.setIDnumber(rs.getString(5));
			user.setPhone(rs.getString(6));
			user.setPostcode(rs.getString(7));
			user.setAddress(rs.getString(8));
			return user;
		}
		rs.close();
		psmt.close();
		return null;
	}

	@Override
	public List<Users> listUsers() throws Exception {
		List<Users> list = new ArrayList<Users>();
		Connection conn = DBUtil.getConn();
		String sql = "select uid,uname,password,email,IDnumber,phone,postcode,address from users";
		PreparedStatement psmt = conn.prepareStatement(sql);
		ResultSet rs = psmt.executeQuery();
		while(rs.next()){
			Users user = new Users();
			user.setUid(rs.getInt(1));
			user.setUname(rs.getString(2));
			user.setPassword(rs.getString(3));
			user.setEmail(rs.getString(4));
			user.setIDnumber(rs.getString(5));
			user.setPhone(rs.getString(6));
			user.setPostcode(rs.getString(7));
			user.setAddress(rs.getString(8));
			list.add(user);
		}
		rs.close();
		psmt.close();
		
		return list;
	}

	

}
